package com.tange.ai.core.demo.add.scan;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.tange.ai.core.demo.Utils;
import com.tange.ai.core.demo.add.ap.WiFiConfigurationActivity;
import com.tange.ai.core.demo.databinding.ActivityQrCodeShowBinding;
import com.tange.core.backend.service.http.HttpConfigurations;
import com.tange.core.backend.service.request.Http;
import com.tange.core.backend.service.request.HttpResponse;
import com.tange.core.backend.service.response.RxResponse;
import com.tange.module.add.match.DeviceMatchQuery;
import com.tange.module.add.wifi.DeviceWiFiConfiguration;
import com.tg.data.http.entity.DeviceMatchBean;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * WiFi配置并生成二维码，然后向设备展示
 */
public class QrCodeShowActivity extends AppCompatActivity {

    private ActivityQrCodeShowBinding binding;

    private String wifiName;
    private String wifiPwd;

    // 用于查询配网结果的token
    private String bindToken;

    private String status = "";

    private final Handler handler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityQrCodeShowBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getSupportActionBar().hide();

        Utils.setStatusBar(this, Color.TRANSPARENT);


        wifiName = getIntent().getStringExtra(WiFiConfigurationActivity.WIFI_NAME);
        wifiPwd = getIntent().getStringExtra(WiFiConfigurationActivity.WIFI_PASSWORD);

        binding.queryMatching.setOnClickListener(v -> queryDeviceMatching());

        generateQrCode();
    }

    private void generateQrCode() {

        // 1. 生成一个 token
        bindToken = DeviceWiFiConfiguration.createBindToken();

        // 2. 生成配网字符串
        String wifiConfig = DeviceWiFiConfiguration.createWiFiConfig(wifiName, wifiPwd, String.valueOf(HttpConfigurations.getInstance().userId()), bindToken);

        // 3. 转化为一个二维码图片，大小为100x100
        Bitmap bimap = DeviceWiFiConfiguration.createQrCode(wifiConfig, 200, 200);


        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) binding.qrCodeIv.getLayoutParams();
        lp.width = getWindowManager().getDefaultDisplay().getWidth();
        lp.height = lp.width;
        binding.qrCodeIv.setLayoutParams(lp);

        binding.qrCodeIv.setVisibility(View.VISIBLE);
        binding.qrCodeIv.setImageBitmap(bimap);
    }

    private void queryDeviceMatching() {
        // 使用 token， 查询 配网结果
        DeviceMatchQuery.create().request(bindToken, new DeviceMatchQuery.Callback() {
            @Override
            public void onSuccess(DeviceMatchBean deviceMatchBean) {
                // 设备配网成功，继续后续业务逻辑，比如设置设备名称
                status = "设备配网成功！ID = " + deviceMatchBean.getId();
                binding.statusTv.setText(status);

                updateDeviceName(deviceMatchBean.getId());

                handler.removeCallbacksAndMessages(null);
            }

            @Override
            public void onError(int errorCode, String errorMsg) {
                // 尚未配网成功
                status = "查询失败 " + errorCode + ", " + errorMsg + ", 5s后再次查询 ...";
                binding.statusTv.setText(status);

                handler.postDelayed(() -> queryDeviceMatching(), 5000);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    private void updateDeviceName(long deviceId) {
        status = status + "\n" + "尝试修改设备名称...";
        binding.statusTv.setText(status);

        Http.INSTANCE.create()
                .path("/device/alter")
                .param("device_id", deviceId)
                .param("name", "我是设备扫码添加的")
                .post()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HttpResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HttpResponse response) {
                        if (response.isSuccess()) {
                            status = status + "\n" + "修改设备名称成功";
                            binding.statusTv.setText(status);
                        } else {
                            status = status + "\n" + "修改设备名称失败";
                            binding.statusTv.setText(status);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        status = status + "\n" + "修改设备名称失败";
                        binding.statusTv.setText(status);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}